#include "head.h"
#include <func.h>

int getCommand(char buf[], char command[]);
int main(int argc, char *argv[]){
    // ./client.c 192.168.31.128 1234 username password
    ARGS_CHECK(argc, 5);
    int sockFd = socket(AF_INET, SOCK_STREAM, 0);  // 创建一个网络套接字
    struct sockaddr_in addr;
    addr.sin_addr.s_addr = inet_addr(argv[1]);
    addr.sin_port = htons(atoi(argv[2]));
    addr.sin_family = AF_INET;
    int ret = connect(sockFd, (struct sockaddr*)&addr, sizeof(addr));   // 发起第一次握手
    ERROR_CHECK(ret, -1, "connet");

    train_t t;
    //发送用户名和密码验证登录
    char sendMsg[1024] = {0};
    sprintf(t.buf, "%s %s", argv[3], argv[4]);
    t.dataLength = strlen(t.buf);
    ret = send(sockFd, &t, sizeof(t.dataLength)+t.dataLength, 0);
    ERROR_CHECK(ret, -1, "send username and password");
    // char result[1024] = {0};
    // recv(sockFd, result, sizeof(result), 0);
    // puts(result);

    while(1){
        bzero(&t, sizeof(train_t));
        int dataLength;
        char bashPre[1024] = {0};
        char line[1024] = {0};
        char responMsg[1024] = {0};
        // ret = recv(sockFd, buf, sizeof(buf), 0);
        // ERROR_CHECK(ret, -1, "recv xxx$");
        // puts(buf);
        // bzero(buf, sizeof(buf));
        recv(sockFd, &dataLength, sizeof(dataLength), 0);
        recv(sockFd, bashPre, dataLength, 0);
        printf("%s\n", bashPre);//pwd$

        fgets(line, sizeof(line), stdin);
        char commandLine[200] = {0};
        strncpy(commandLine, line, strlen(line)-1);
        puts(commandLine);
        strncpy(t.buf, line, strlen(line)-1);
        t.dataLength = strlen(t.buf);
        printf("length = %d, line = %s\n", t.dataLength, t.buf);
        send(sockFd, &t, sizeof(dataLength)+t.dataLength, 0);//发送命令

        char command[1024] = {0};
        getCommand(commandLine, command);
        printf("%s\n", command);

        if(strcmp(command, "cd") == 0){
            cd(sockFd);
        } 
        else if(strcmp(command, "ls") == 0 ){
            ls(sockFd);
        }
        else if(strcmp(command, "pwd") == 0){
            pwd(sockFd);
        }
        else if(strcmp(command, "remove") == 0){
            rm(sockFd);
        }
        else if(strcmp(command, "puts") == 0){
            puts("if puts");
            upload(line, sockFd);
        }
        else if(strcmp(command, "gets") == 0){
            recvFile(line, sockFd);
        }
        else if(strcmp(command, "mkdir") == 0){
            makedir(sockFd);
        }
        else if(strcmp(command, "exit") == 0){

        }
    }

}


// 根据用户的一整条命令buf 分析出命令的种类，存到command里
int getCommand(char buf[], char command[]){
    for(int i = 0; i < strlen(buf); ++i){
        if(buf[i] == ' ')
            break;
        command[i] = buf[i];
    }
}
